package com.wpq.netty.discard;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

public class TimeServerHandler extends ChannelInboundHandlerAdapter{
//    @Override
//    public void channelActive(final ChannelHandlerContext ctx){
//       final ByteBuf time= ctx.alloc().buffer();
//       time.writeInt((int)(System.currentTimeMillis()/1000L+2208988800L));
//       final ChannelFuture f=ctx.writeAndFlush(time);
//       f.addListener(new ChannelFutureListener() {
//           @Override
//           public void operationComplete(ChannelFuture future) throws Exception {
//               assert  f==future;
//               ctx.close();
//           }
//       });
//    }
    //两个生命周期的监听方法
    private  ByteBuf buf;
    @Override
    public void handlerAdded(ChannelHandlerContext ctx){
        buf = ctx.alloc().buffer();
    }
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx){
        buf.release();
        buf = null;
    }
    public void channelRead(ChannelHandlerContext ctx,Object msg){
        ByteBuf m=(ByteBuf)msg;
        buf.writeBytes(m); //所有接收的数据都应该被累计在buf变量里
        m.release();
        if(buf.readableBytes()>=4){
            long currentTimeMillis =(buf.readUnsignedInt()-2208988800L)*1000L;
            System.out.println(new Date(currentTimeMillis));
            ctx.close();
        }
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
        cause.printStackTrace();
        ctx.close();
    }
}
